<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :showBack="true">
  </pageHeader>
  <div class="head">
    <a-row class="grid-demo" :gutter="[24, 12]">
      <a-col :span="7">
        <div>
          生产工单编号：
          <span>{{ data?.workOrderCode }}</span>
        </div>
      </a-col>
      <a-col :span="7">
        <div>
          客户名称：
          <span>{{ data?.materialName }}</span>
        </div>
      </a-col>
      <a-col :span="7">
        <div>
          已排计划数：
          <span>{{ data?.scheduledTaskNumber }}</span>
        </div>
      </a-col>

      <a-col :span="7">
        <div>
          产品编码：
          <span>{{ data?.planCode }}</span>
        </div>
      </a-col>
      <a-col :span="7">
        <div>
          物料名称：
          <span>{{ data?.materialName }}</span>
        </div>
      </a-col>
      <a-col :span="7">
        <div>
          规格型号：
          <span>{{ data?.materialNumber }}</span>
        </div>
      </a-col>
      <a-col :span="7">
        <div>
          计划日期：
          <span>{{
            `${dayjs(data.startDate).format('YYYY-MM-DD')} --${dayjs(
              +new Date(data.startDate) + 7 * 24 * 60 * 60 * 1000
            ).format('YYYY-MM-DD')}`
          }}</span>
        </div>
      </a-col>
    </a-row>
  </div>
  <tableTurn :tableData="taskDataShow" ref="tableRef">
    <a-table-column :width="70" align="center">
      <template #title> 序号 </template>
      <template #cell="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      data-index="planNumber"
      title="计划数量"
      align="center"
    >
    </a-table-column>
    <a-table-column
      :width="150"
      data-index="awaitplanNumber"
      title="待计划数量"
      align="center"
    >
    </a-table-column>
    <a-table-column
      :width="150"
      data-index="planTaskNumber"
      title="计划任务数量"
      align="center"
    >
      <template #title>
        <div class="title_before">计划任务数量</div>
      </template>
      <template #cell="{ record }">
        <a-input-number
          :min="1"
          @change="calculate"
          :max="data.produceNumber"
          v-model="record.planTaskNumber"
        />
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      data-index="batchCode"
      title="生产批次号"
      align="center"
    >
      <template #cell="{ record }">
        <a-input v-model="record.batchCode" />
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      data-index="beginAt"
      title="计划开工时间"
      align="center"
    >
      <template #cell="{ record }">
        <a-date-picker
          value-format="timestamp"
          v-model="record.beginAt"
          show-time
          format="YYYY-MM-DD HH:mm"
        />
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      data-index="endAt"
      title="计划完工时间"
      align="center"
    >
      <template #cell="{ record }">
        <a-date-picker
          value-format="timestamp"
          v-model="record.endAt"
          show-time
          format="YYYY-MM-DD HH:mm"
        />
      </template>
    </a-table-column>
    <a-table-column :width="150" fixed="right" title="操作" align="center">
      <template #cell="{ rowIndex }">
        <a-button
          v-if="rowIndex === 0"
          @click="controls(rowIndex)"
          type="outline"
        >
          拆分
        </a-button>
        <a-button
          v-else
          @click="controls(rowIndex)"
          type="outline"
          status="danger"
        >
          删除
        </a-button>
      </template>
    </a-table-column>
  </tableTurn>

  <div class="foot">
    <a-space style="margin-right: 20px">
      <a-button @click="router.back()"> 取消 </a-button>
      <a-button type="primary" @click="add"> 提交 </a-button>
    </a-space>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onBeforeUnmount, computed } from 'vue';

  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import pageHeader from '@/components/page-header/index.vue';
  import { Message } from '@arco-design/web-vue';
  import { PostTasks } from '@/api/produce-management/produce-list/index';
  import type { ProduceTask } from '@/api/produce-management/produce-list/type';

  interface TtaskData {
    producePlanId?: number;
    planNumber: number;
    awaitplanNumber?: number;
    planTaskNumber: number;
    batchCode?: string;
    beginAt?: number;
    endAt?: number;
  }
  const router = useRouter();
  const title: string = '创建生产任务';
  const data = reactive(
    JSON.parse(localStorage.getItem('weeklyPlanData') as string)
  );

  const tableRef = ref();
  const taskData = reactive<{ data: TtaskData[] }>({
    data: [
      {
        producePlanId: data?.id,
        planNumber: data?.produceNumber,
        awaitplanNumber:
          (data?.produceNumber ? Number(data?.produceNumber) : 0) -
          (data?.scheduledTaskNumber ? Number(data?.scheduledTaskNumber) : 0),
        planTaskNumber: 0,
      },
    ],
  });

  const breadCrumb: string[] = ['生产管理', '生产工单', '创建生产任务'];
  // 计算函数
  const calculate = () => {
    const newData: TtaskData[] = [];
    let sum = 0;
    taskData.data.forEach((ele) => {
      const newObj = ele;
      if (newObj.planTaskNumber) {
        sum += Number.isNaN(newObj.planTaskNumber) ? 0 : newObj.planTaskNumber;
      } else {
        sum += 0;
      }
      newObj.awaitplanNumber =
        newObj.planNumber -
        sum -
        (data?.scheduledTaskNumber ? Number(data?.scheduledTaskNumber) : 0);
      newData.push({ ...ele });
    });
    taskData.data = newData;
    tableRef.value.loadData();
  };
  const taskDataShow = () => {
    return Promise.resolve(taskData.data);
  };
  const total = computed(() => {
    return taskData.data.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.planTaskNumber
        ? currentValue.planTaskNumber
        : 0;
    }, 0);
  });
  onBeforeUnmount(() => {
    localStorage.removeItem('weeklyPlanData');
  });
  // 拆分与分解
  const controls = (index: number) => {
    if (index) {
      taskData.data.splice(index, 1);
      return;
    }
    const addplanTaskNumber = taskData.data[0].planTaskNumber;
    const awaitplanNumber =
      data.produceNumber -
      total.value -
      (data?.scheduledTaskNumber ? Number(data?.scheduledTaskNumber) : 0);
    if (addplanTaskNumber && addplanTaskNumber <= awaitplanNumber) {
      taskData.data.push({
        producePlanId: data.id,
        planNumber: data.produceNumber,
        awaitplanNumber:
          awaitplanNumber -
          addplanTaskNumber -
          (data?.scheduledTaskNumber ? Number(data?.scheduledTaskNumber) : 0),
        planTaskNumber: addplanTaskNumber,
      });
    } else if (addplanTaskNumber > awaitplanNumber) {
      Message.error('拆分数量不能大于待计划数量');
    } else {
      Message.error('拆分数量不能为0');
    }
  };
  // 新增
  const add = async () => {
    try {
      // if (total.value < data.produceNumber) {
      //   Message.error('任务数量小于计划数量');
      //   return;
      // }
      // if (total.value > data.produceNumber) {
      //   Message.error('任务数量大于计划数量');
      //   return;
      // }
      const arr: ProduceTask[] = [];
      let sum = 0;
      taskData.data.forEach((ele) => {
        const { producePlanId, batchCode, planTaskNumber, beginAt, endAt } =
          ele;
        if (!planTaskNumber) {
          throw new Error('计划任务数量不能为空');
        }
        sum += planTaskNumber;
        arr.push({ producePlanId, batchCode, planTaskNumber, beginAt, endAt });
      });

      if (
        sum > data.produceNumber ||
        sum > Number(data.produceNumber) - data.scheduledTaskNumber
      ) {
        //
        throw new Error('任务数量大于未排计划数量');
      }

      await PostTasks({ produceTasks: arr });
      Message.info('新增成功');
      router.back();
    } catch (error) {
      console.log(error);
      Message.error(`${error}`);
    }
  };
</script>

<style lang="less" scoped>
  .head {
    width: 100%;
    padding: 20px;
  }
  .foot {
    padding-top: 10px;
    margin-top: 10px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
  }
  .title_before {
    position: relative;
  }
  .title_before::before {
    content: '*';
    color: red;
    font-size: 16px;
  }
</style>
